package com.hehanpeng.springbootnetty.client.cib;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.UnsupportedEncodingException;

/**
 * Netty 客户端
 */
public class CibNettyClient {

    public void connect(int port, String host, byte[] bytes) throws Exception {
        //客户端启动类
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer() {
                        @Override
                        protected void initChannel(Channel ch) {
                            ch.pipeline().addLast(new CibSimpleMessageToByteEncoder());
                            ch.pipeline().addLast(new CibSimpleByteToMessageDecoder());
                            ch.pipeline().addLast(new CibClientHandler(bytes));
                        }
                    });

            //同步等待
            ChannelFuture future = bootstrap.connect(host, port).sync();
            //等待客户端连接端口关闭
            future.channel().closeFuture().sync();
        } finally {
            //优雅关闭 线程组
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String content = "00990200B23000010000000004000000100000003020000000000012340303145843000042哈哈08030900003010804025370";
         content = "0075082082200001000000000400000010000000030314584300004208030900003010804025370";
        byte[] reqByte = content.getBytes("UTF-8");
        int port = 10006;
        CibNettyClient client = new CibNettyClient();
        try {
            client.connect(port, "10.39.14.102", reqByte);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}